import { Directive } from "vue";


const entLoading: Directive = {
  mounted(el, binding) {
    const fn = binding.value;   
    el.onclick = async (...args) => {
      if (el.getAttribute('aria-disabled') === 'true') return; 
      try {
        el.classList.add('is-loading');
        el.setAttribute('aria-disabled', 'true');     
        const span = document.createElement('span');
        span.className = 'el-loading-spinner';
        span.innerHTML = `
          <svg class="circular" viewBox="25 25 50 50">
            <circle class="path" cx="50" cy="50" r="20" fill="none"/>
          </svg>
        `;
        const style = document.createElement('style');
        style.textContent = `
          .el-button {
            position: relative;
          }
          .el-loading-spinner {
            position: absolute;
            left: 12px;
            top: 120%;
            transform: translateY(-50%);
          }
          .el-loading-spinner .circular {
            width: 16px;
            height: 16px;
            animation: loading-rotate 2s linear infinite;
            vertical-align: middle;
          }
          .el-loading-spinner .path {
            stroke-dasharray: 90,150;
            stroke-dashoffset: 0;
            stroke-width: 2;
            stroke: currentColor;
            stroke-linecap: round;
            animation: loading-dash 1.5s ease-in-out infinite;
          }
          .el-button.is-loading span:not(.el-loading-spinner) {
            margin-left: 24px;
          }
          @keyframes loading-rotate {
            100% {
              transform: rotate(360deg);
            }
          }
          @keyframes loading-dash {
            0% {
              stroke-dasharray: 1,200;
              stroke-dashoffset: 0;
            }
            50% {
              stroke-dasharray: 90,150;
              stroke-dashoffset: -40px;
            }
            100% {
              stroke-dasharray: 90,150;
              stroke-dashoffset: -120px;
            }
          }
        `;
        document.head.appendChild(style);
        el.insertBefore(span, el.firstChild);
        await fn?.(...args);
      } catch (error) {
        console.error('Button action error:', error);
      } finally {
        el.classList.remove('is-loading');
        el.setAttribute('aria-disabled', 'false');  
        // 移除 loading 效果
        const loadingSpinner = el.querySelector('.el-loading-spinner');
        if (loadingSpinner) {
          el.removeChild(loadingSpinner);
        }       
        // 恢复文本位置
        const textSpan = el.querySelector('span:not(.el-loading-spinner)');
        if (textSpan) {
          textSpan.style.marginLeft = '';
        }
      }
    };
  }
};

export default entLoading;


